<template>
  <div>
    <div class="h12" />
    <el-card>
      <div slot="header" class="clearfix">
        <b>设备控制</b>
      </div>
      <div class="action-container">
        <el-row>
          <div v-for="(item,index) in rtuActionDisplays" :key="index">
            <el-col v-if="item.action_type == 'select'" :span="6" style="margin:8px 0;">
              <div class="action-board">
                <b>{{ item.name }}：</b>
                <el-button-group>
                  <el-button
                    v-for="(citem,cindex) in item.action_arr"
                    :key="cindex"
                    size="medium"
                    :type="getButtonType(item,cindex)"
                    @click="sendCommand(citem, item.rtu_serialno)"
                  >{{ citem.name }}</el-button>
                </el-button-group>
              </div>
            </el-col>
          </div>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import { sendCommand } from '@/api/device'
import { mapGetters } from 'vuex'
export default {
  props: {
    rtuActionDisplays: {
      type: Array,
      default() {
        return []
      }
    },
    states: {
      type: Object,
      default() {
        return {}
      }
    },
    serialno: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      sliderValue: 0
    }
  },
  computed: {
    ...mapGetters(['lang'])
  },
  watch: {
    rtuActionDisplays: {
      handler(newVal, oldVal) {
        this.rtuActionDisplays.map(val => {
          if (typeof (val.action_arr) === 'string') {
            val.action_arr = JSON.parse(val.action_arr)
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    sendCommand(item, rtu_serialno) {
      this.$confirm(this.$t('common.controlConfirmDesc'), this.$t('common.operationConfirm'), { type: 'warning' }).then(() => {
        const data = {
          namekey: item.namekey,
          value: item.params
        }
        this._sendCommand(data, rtu_serialno)
      })
    },
    async _sendCommand(data, rtu_serialno) {
      const res = await sendCommand(data, rtu_serialno)
      if (res.errorCode === 0) {
        this.$message.success(this.$t('common.actionSuccess'))
      }
    },
    getButtonType(item, cindex) {
      if (item.show_state) {
        const state_arr = JSON.parse(item.state_arr)
        const state = +this.states[state_arr.namekey]
        return state === state_arr.state[cindex] ? 'primary' : 'default'
      }
      return 'default'
    }
  }
}
</script>

<style lang="scss" scoped>
.action-board{
  b{
    display:inline-block;
    min-width:100px;
    text-align:right;
  }
}
</style>
